package com.coocaa.cirrus.common.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2025/7/11 15:47
 * @description
 */
@UtilityClass
public class JsonUtil {
    private static SerializeConfig mapping = new SerializeConfig();

    public static String obj2JsonDisableCircularRef(Object obj) {
        return JSON.toJSONString(obj, mapping, SerializerFeature.DisableCircularReferenceDetect);
    }

    public static Map<String, Object> json2MapObj(String jsonString) {
        return (Map) JSON.parse(jsonString);
    }

    public static Object json2Object(String jsonString, Class<?> classOfT) {
        return JSON.toJavaObject(JSON.parseObject(jsonString), classOfT);
    }

    public static String obj2Json(Object obj) {
        return JSON.toJSONString(obj, mapping, new SerializerFeature[0]);
    }

    public static <T> List<T> json2ObjectLists(String jsonString, Class<?> cls) {
        ArrayList list = InstanceUtil.newArrayList(0);
        try {
            JSONArray jsonArray = JSON.parseArray(jsonString);
            if (jsonArray != null && jsonArray.size() > 0) {
                list = new ArrayList();
                for (int i = 0; i < jsonArray.size(); ++i) {
                    Object object = jsonArray.get(i);
                    if (cls.equals(object.getClass())) {
                        list.add(object);
                    } else {
                        Object model = JSONObject.toJavaObject((JSONObject) object, cls);
                        list.add(model);
                    }

                }
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }
        return list;
    }

}
